﻿using PLCS.Domain.Processes;
using PLCS.EntityFrameworkCore.EntityFrameworkCore;

namespace PLCS.EntityFrameworkCore.Processes;

internal class ProcessRepository : EfCoreRepository<PLCSDbContext, Process, Guid>, IProcessRepository
{
    public ProcessRepository(IDbContextProvider<PLCSDbContext> dbContextProvider) : base(dbContextProvider)
    {
    }

    /// <summary>
    /// 通过工艺编号找到工艺
    /// </summary>
    /// <param name="processNo"></param>
    /// <returns></returns>
    public async Task<Process?> FindProcessByNoAsync(string processNo)
    {
        var process = await FindAsync(x => x.ProcessNo == processNo);
        return process;
    }

    /// <summary>
    /// 新增触发器
    /// </summary>
    /// <param name="trigger"></param>
    /// <returns></returns>
    public async Task<Trigger> InsertTriggerAsync(Trigger trigger)
    {
        var dbContext = await GetDbContextAsync();

        var savedEntity = (await dbContext.Set<Trigger>().AddAsync(trigger)).Entity;
        await dbContext.SaveChangesAsync();
        return savedEntity;
    }

    /// <summary>
    /// 寻找触发器
    /// </summary>
    /// <param name="predicate"></param>
    /// <returns></returns>
    public async Task<Trigger?> FindTriggerAsync(Func<Trigger, bool> predicate)
    {
        var dbConext = await GetDbContextAsync();
        return dbConext.Triggers.Where(predicate).FirstOrDefault();
    }
}